<?php

class GroupInfoModel
{
	private $groupKeyPrefix =   'GI/';
	private $groupCatsKeyPrefix     =   'GCT/';
    private $activityKeyPrefix      =   'ACT/';
	private $diaryListCacheModel;
	private $commonHotDiaryTopics = array();
	private $officialHotDiaryTopics = array();
	
	public function __construct(){
		$this->diaryListCacheModel  =   new DiaryListCacheModel();
	}
	
	#建立小组
	public function createGroup($info)/*{{{*/
	{
		if (empty($info['uid']))
		{
			AC::$errorNo    =   'GRM001';
			return  FALSE;
		}
		
		$data = array();
		#小组名10个字
		$data['name']       	 =	UK::getstr($info['name'], AC::GROUP_NAME_LENGTH,'',1);
		#小组介绍200个字
		$data['introduction']    =	UK::getstr($info['introduction'], AC::GROUP_INTRO_LENGTH,'',1);
		if (strlen($data['name']) < 1 || strlen($data['introduction']) < 1){
			AC::$errorNo    =   'GRM001';
			return  FALSE;
		}
		
		$data['uid']        	 =   intval($info['uid']);
        $data['time']       	 =   AC::SERVER_TIME;
        $data['gtype']       	 =   AC::GROUP_CIRCLE_TYPE;
        isset($info['cover'])			&& $data['cover'] 		  = strval($info['cover']);
        isset($info['secret']) 			? $data['secret'] 		  = intval($info['secret'])         : 0;
        isset($info['category']) 		? $data['category'] 	  = intval($info['category'])       : 1;
        isset($info['max_member_num'])  ? $data['max_member_num'] = intval($info['max_member_num']) : 0;
        isset($info['extras'])  ? $data['extras']  = $info['extras'] : '';
    
        #小组名唯一
        #FALSE	小组名已有
        $check = $this->checkName($data);
		if ($check)
		{
			AC::$errorNo	=	'GRM007';
			return FALSE;
		}
        $key    =   $this->groupKeyPrefix. 0;
        $result =   Storage::addData($key, $data);
        if (empty($result))
        {
        	AC::$errorNo = 'GRM002';
        	return FALSE;
        }
        $this->diaryListCacheModel->addGroupUser($result, $data['uid'], '1767024002');
        return  $result;
	}/*}}}*/
	
	#解散小组
	public function removeGroup($info)/*{{{*/
	{
		$key    =   $this->groupKeyPrefix. 0;
		$data	=   array('status' => '1');
		$where  =   array('gid' => $info['gid'],'uid'=>$info['uid']);
		$result =   Storage::setConditionData($key, $data, $where);
		return  $result;
	}/*}}}*/
	
	#删除
	public function delGroup($gid)/*{{{*/
	{
		$key    =   $this->groupKeyPrefix. 0;
		$where  =   array('gid' => $gid);
		$result =   Storage::delConditionData($key, $where);
	
		return  $result;
	}/*}}}*/
	
	#单个小组信息
	public function getGroupInfo($info)/*{{{*/
	{
		if (empty($info['gid']))
		{
			AC::$errorNo    =   'GRM001';
			return FALSE;
		}
		
		$key   	   =   $this->groupKeyPrefix. 0;
		$where     =   array('gid' => $info['gid'],'status'=>0,'gtype'=>1);
		$result	   =   Storage::getConditionData($key, $where);
		return $result;
	}/*}}}*/

	#我创建的圈子
	public function getMeCreateGroup($info)/*{{{*/
	{
		if (empty($info['uid']))
		{
			AC::$errorNo    =   'GRM001';
			return FALSE;
		}
		
		$key   =   $this->groupKeyPrefix. 0;
		$where =   array('uid' => $info['uid'],'status'=>0,'gtype'=>1);
		$order = " time DESC";
		$result	   =   Storage::getConditionManyData($key, $where, $order);
		return $result;
	}/*}}}*/
	
	#多个小组信息
	public function manyGroupInfo($info)/*{{{*/
	{
		if (empty($info))
		{
			AC::$errorNo    =   'GRM001';
			return FALSE;
		}
		
		$key    =   $this->groupKeyPrefix. 0;
		foreach ($info as $val)
		{
			//$where  =   array('gid' => $val['gid']);
			$where    =   array('gid' => $info['gid'],'status'=>0,'gtype'=>1);
			$result[] =   Storage::getConditionData($key, $where);
		}
		
		return $result;
	}/*}}}*/
	
	#所有组
	public function allGroup($info)/*{{{*/
	{
		$start  =   0;
        $length =   AC::GROUP_LIST_DISPLAY_LEN;
        isset($info['start'])   &&  $start  =   $info['start'];
        isset($info['length'])  &&  $length =   $info['length'];
        if ($start  <   0)  $start  =   0;
        
        $key    =   $this->groupKeyPrefix. 0;
        //$where  =   " status = 0 AND gid <= ".AC::$groupMaxGid;
        $where  =   " status = 0 AND gtype = 1";
        if (!empty($info['category'])){
            //$where  =   " status = 0 AND gid <= ".AC::$groupMaxGid." AND category = ".intval($info['category']);
            $where  =   " status = 0 AND gtype = 1 AND category = ".intval($info['category']);
        }
        
        $orderBy=   ' display_order DESC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
	
		return $result;
	}/*}}}*/

    public function getGroupByCategory($category, $start=0, $length = AC::GROUP_LIST_DISPLAY_LEN) {
        $key    =   $this->groupKeyPrefix. 0;
        $where  =   " status = 0 AND gtype = 1 AND category = " . $category;
        if($start < 0) $start = 0;
        $orderBy=   ' topic_num DESC,member_num DESC ';
        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);

        return $result;
    }

    /**
     * 用户置顶
     * @param $uid
     * @return array
     */
    public function getUserTopGroup($uid){
        $userGroupInfo = $this->diaryListCacheModel->getUserGroupAllCache($uid);
        $topGid = array();
        if(isset($userGroupInfo['topGid']) && !empty($userGroupInfo['topGid'])) {
            $topGid = explode(',', $userGroupInfo['topGid']);
        }
        return $topGid;
    }

    public function getChoiceGroup($start, $len){
        $key = $this->activityKeyPrefix . 0;
        $where = 'type = "choicegroup" AND status = 0 AND end > '. AC::SERVER_TIME;
        $orderBy = 'sort desc';
        $start = empty($start) ? 0 : $start;
        $length = empty($len) ? 5 : $len;
        $result = Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        return $result;
    }

    /**
     * 获取该分类下圈子列表
     * @param $category
     * @param int $start
     * @param int $length
     * @return array
     */
    public function getGroupListByCategory($category, $start = 0, $length = AC::GROUP_LIST_DISPLAY_LEN){
        $len = $start + $length;
        $list = $this->diaryListCacheModel->getGroupListByCategory($category, 0, -1);
        //todo 当前版本缓存强制更新
        $list = [];
        if(empty($list)){
            $key    =   $this->groupKeyPrefix. 0;
            $where = " status = 0 AND gtype = 1 AND uid = 2 AND category = ". $category;
            //该分类的官方圈子
            $officialGroups = Storage::getConditionManyData($key, $where);
            //官方圈子列表
            $officialGid = $this->getOfficialGroup();
            //分类置顶圈子列表
            $topGid = $this->diaryListCacheModel->getTopGroups($category);
            //按照话题排序
            $groupList = $this->getGroupByCategory($category, 0, 200);
            $i = 0;
            foreach ($officialGroups as $value){
                //官方圈子置顶
                $i+=1;
                $score = 9999999 - $i;
                $grouInfo = $this->groupAddRedis($value['gid']);
                if(empty($grouInfo)) continue;
                $this->diaryListCacheModel->addGroupListByCategory($category, $score, $value['gid']);
            }
            foreach ($topGid as $gid){
                //分类圈子置顶
                $i+=1;
                $score = 9899999 - $i;
                $grouInfo = $this->groupAddRedis($gid);
                if(empty($grouInfo)) continue;
                $this->diaryListCacheModel->addGroupListByCategory($category, $score, $gid);
            }
            foreach ($groupList as $value){
                if (in_array($value['gid'], $officialGid) || in_array($value['gid'], $topGid)) {
                    continue;
                }
                $score = $value['topic_num'];
                $grouInfo = $this->groupAddRedis($value['gid']);
                if(empty($grouInfo)) continue;
                $this->diaryListCacheModel->addGroupListByCategory($category, $score, $value['gid']);
            }
        }
        if($len > 300){
            //官方圈子列表
            $officialGid = $this->getOfficialGroup();
            //分类置顶圈子列表
            $topGid = $this->diaryListCacheModel->getTopGroups($category);
            //按照话题排序
            $groupList = $this->getGroupByCategory($category, 0, 200);
            $result = [];
            foreach ($groupList as $value){
                if (in_array($value['gid'], $officialGid) || in_array($value['gid'], $topGid)) {
                    continue;
                }
                $result[] = $value['gid'];
            }
            return $result;
        }
        $list = $this->diaryListCacheModel->getGroupListByCategory($category, 0, -1);
        $groupList = [];
        foreach ($list as $value){
            $pauseList = $this->diaryListCacheModel->getPauseGroupList();
            if(in_array($value, $pauseList)) {
                continue;
            }
            $groupInfo  		= $this->groupAddRedis($value);
            if(empty($groupInfo) || $category != $groupInfo['category'] || $groupInfo['category']  == 12){
                continue;   //不存在及淘汰分类
            }
            $groupList[] = $value;
        }
        $list = array_slice($groupList, $start, $length);
        return $list;
    }

    public function addGroupToCategory($gid){
        $groupInfo = $this->groupAddRedis($gid);
        if(empty($groupInfo)){
            return false;
        }
        $firstInfo = $this->diaryListCacheModel->getGroupRangeByCategory($groupInfo['category'], 0, 1);
        $oldGroupInfo = $this->groupAddRedis($firstInfo[0]);
        $count = $this->diaryListCacheModel->getCountGroupListByCategory($groupInfo['category']);
        //如果缓存列表已达到300，且最后一个圈子的话题数也比当前圈子多，则不加缓存
        if($oldGroupInfo['topic_num'] > $groupInfo['topic_num'] && $count >= 300){
            return true;
        }
        $this->diaryListCacheModel->addGroupListByCategory($groupInfo['category'], $groupInfo['topic_num'], $gid);
        return true;
    }

    /**
     * 官方圈子
     * @param $start
     * @param $len
     * @return array|bool|mixed
     */
    public function getOfficialGroup($start=0, $len=-1) {
        $result = $this->diaryListCacheModel->getOfficialGroupCache($start, $len);
        if(!empty($result)) {
            return $result;
        }
        $key = $this->groupKeyPrefix . 0;
        $where = " status = 0 AND gtype = 1 AND uid = 2";
        $groupList = Storage::getConditionManyData($key, $where);
        if(empty($groupList)) return array();
        $this->diaryListCacheModel->delOfficialGroupCache();
        foreach ($groupList as $value){
            $this->diaryListCacheModel->addOfficialGroupCache($value['gid']);
        }
        $result = $this->diaryListCacheModel->getOfficialGroupCache($start, $len);
        return $result;
    }
	
	#修改小组
	public function editGroup($info)/*{{{*/
	{
		if (intval($info['gid']) < 1)
		{
			AC::$errorNo    =   'GRM001';
			return  FALSE;
		}

        #小组名唯一
        #FALSE	小组名已有
        if(isset($info['name'])) {
            $check = $this->checkName($info);
            if ($check) {
                AC::$errorNo = 'GRM007';
                return FALSE;
            }
        }
		
		$data = array();
		isset($info['display_order'])  && $data['display_order']  =   $info['display_order'];
		isset($info['name'])           && $data['name']     	  =   $info['name'];
		isset($info['introduction'])   && $data['introduction']   =   $info['introduction'];
		isset($info['mUid'])           && $data['mUid']           =   $info['mUid'];
		isset($info['cover'])          && $data['cover']     	  =   $info['cover'];
		isset($info['category'])       && $data['category']       =   $info['category'];
		isset($info['top_tids'])       && $data['top_tids']       =   $info['top_tids'];
		isset($info['mUids'])          && $data['mUids']       	  =   $info['mUids'];
		isset($info['uid'])            && $data['uid']       	  =   $info['uid'];
		isset($info['extras'])         && $data['extras']        =    $info['extras'];
		
		if (empty($data)){
		    return TRUE;
		}
		
		$key    =   $this->groupKeyPrefix. 0;
		$where  =   array('gid' => $info['gid'],'gtype'=>1);
		$result =   Storage::setConditionData($key, $data, $where);
		
		return  $result;
	}/*}}}*/
	
	#我管理的小组列表
	public function getMeGroupList($info)/*{{{*/
	{
		if (empty($info['uid']))
		{
			AC::$errorNo    =   'GRM001';
			return FALSE;
		}
		
		
		$start  =   isset($info['start'])  ?   $info['start'] :   0;
		$length =   isset($info['length']) ?   $info['length']:   AC::DIARY_LIST_DEFAULT_LEN;

		if ($start  <   0)  $start  =   0;
		

		$where  =   array('uid' => $info['uid'],'status'=>'0','gtype'=>1);
		if (intval($info['id']) > 0) {
		    $where  =   ' gid < '. $info['id']. ' AND uid = '. $info['uid']. ' AND status = 0 AND gtype = 1';
		}
		$key    =   $this->groupKeyPrefix. 0;
		$orderBy=   ' gid DESC ';
		
		$result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
		return  $result;
		
	}/*}}}*/
	
	#发现小组
	public function findGroup($info)/*{{{*/
	{
		if (empty($info['gid']) && empty($info['name']))
		{
			AC::$errorNo    =   'GRM001';
			return FALSE;
		}
		$start  =   0;
	        $length =   AC::GROUP_LIST_DISPLAY_LEN;
	        isset($info['start'])   &&  $start  =   $info['start'];
	        isset($info['length'])  &&  $length =   $info['length'];
	        if (!empty($info['gid']))        $like[] =   ' `gid` = '. $info['gid'].' AND status = 0 AND gtype = 1';
	        if (!empty($info['name']))  	 $like[] =   ' `name` like "%'. $info['name']. '%" AND status = 0 AND gtype = 1';
	        if (empty($like))   $where  =   NULL;
	        else    $where  =   implode(' AND ', $like);
	        if(!empty($info['id']) && empty($info['gid'])) {
                $where .= " AND gid < " . $info['id'];
            }
	        if ($start  <   0)  $start  =   0;

	        $orderBy=   ' gid DESC ';
	        $key    =   $this->groupKeyPrefix. 0;
	        $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
	        return  $result;
	}/*}}}*/
	
	#已创建小组数
	public function getCreatedGroupNum($info)/*{{{*/
	{
		$key       =   $this->groupKeyPrefix. 0;
		$where 	   =   array('uid' => $info['uid'],'status'=>0,'gtype'=>1);
		$result    =   Storage::countDataRow($key, $where);
		
		return $result;
	}/*}}}*/
	
	#私密组不能公开
	public function checkIsSecret($info)/*{{{*/
	{
		$groupInfo = $this->groupInfo($info);
		if ($groupInfo['secret'] == 1 && $info['secret'] == 0)
		{
			AC::$errorNo    =   'GRM005';
			return  FALSE;
		}
			
		return TRUE;
	}
	
	#小组名唯一
	public function checkName($info)/*{{{*/
	{
		$key       =   $this->groupKeyPrefix. 0;
		$where =   array('name' => $info['name']);
		$orderBy = ' gid DESC ';
		
		$result    =   Storage::getConditionData($key, $where, $orderBy);
		return $result;
	}/*}}}*/
	
	#组员退出要减1，修改了memberNum的传参
	public function delMemberNum($info, $gtype = 0)/*{{{*/
	{
		if (empty($info['gid']))
		{
			AC::$errorNo    =   'GRC001';
			return  FALSE;
		}
		
		$data   =   array();
		$data['member_num']   =   -1;
		
		$key    =   $this->groupKeyPrefix. 0;
		$where  =   array('gid' => $info['gid'], 'gtype' => $gtype);
		$result =   Storage::changeNumValueAdd($key, $data, $where);
		return  $result;
	}/*}}}*/

	#组员加入要加1，修改了memberNum的传参
	public function addMemberNum($info, $gtype = 0)/*{{{*/
	{
		if (empty($info['gid']))
		{
			AC::$errorNo    =   'GRC001';
			return  FALSE;
		}
	
		$data   =   array();
		$data['member_num']   =   1;
	
		$key    =   $this->groupKeyPrefix. 0;
		$where  =   array('gid' => $info['gid'], 'gtype' => $gtype);
		$result =   Storage::changeNumValueAdd($key, $data, $where);
		return  $result;
	}/*}}}*/
	
	#删除话题，topicNum减1
	public function delTopicNum($info, $gtype = 0)/*{{{*/
	{
		if (empty($info['gid']))
		{
			AC::$errorNo    =   'GRM001';
			return  FALSE;
		}
		
		$data   =   array();
		$data['topic_num']   =   -1;
		
		$key    =   $this->groupKeyPrefix. 0;
		$where  =   array('gid' => $info['gid'], 'gtype' => $gtype);
		$result =   Storage::changeNumValueAdd($key, $data, $where);
		return  $result;
	}/*}}}*/
	
	#发布话题，topicNum加1
	public function addTopicNum($info, $gtype = 0)/*{{{*/
	{
		if (empty($info['gid']))
		{
			AC::$errorNo    =   'GRM001';
			return  FALSE;
		}
		
		$data   =   array();
		$data['topic_num']   =   1;
		
		$key    =   $this->groupKeyPrefix. 0;
		$where  =   array('gid' => $info['gid'], 'gtype' => $gtype);
		$result =   Storage::changeNumValueAdd($key, $data, $where);
		return  $result;
	}/*}}}*/
	
	// 添加默认圈子
	public function initMember($info)/*{{{*/
	{
	    // 默认加入圈子列表,对应者圈子的id
	    $tmp    =   "gid in(".AC::$initGroupsStr.")";
	    $sql    =   " UPDATE xxtShare.group_0 SET member_num = member_num + 1 WHERE ".$tmp;
	    
	    $key    =   $this->groupKeyPrefix. 0;
	    $result =   Storage::execDbSentence($key, $sql);
	    return  $result;
	}/*}}}*/
	
	// 搜索日记
	public function getSearchTopicInfo($info)/*{{{*/
	{
	    $start  =   0;
	    $length =   AC::FEED_LIST_DISPLAY_LEN;
	    isset($info['start'])   &&  $start  =   $info['start'];
	    isset($info['length'])  &&  $length =   $info['length'];
	    if (intval($start)  <   0)  $start  =   0;
	
	    $ids = array();
	    if (!empty($info['key_word'])){
	        
	        $list = $this->sphinxSearch($info['key_word'], $start, $length);
	        if (!empty($list['matches'])){
	            foreach ($list['matches'] as $val){
	                $tmp = array();
	                $tmp['tid']     = $val['id'];
	                $ids[]         = $tmp;
	            }
	        }
	    }
	
	    return  $ids;
	}/*}}}*/
	
	// 搜索
	private function sphinxSearch($keyword, $start, $length){
	    $client = RedisPool::initSphinx();
	    if (empty($client)) return array();
	    // 设置返回数据的排序
	    $client->setSortMode(SPH_SORT_ATTR_DESC, 'time');
	    // 分页
	
	    $client->SetLimits($start, $length, '1000');
	    // 搜索,1=日记,2=用户,3=话题
	    $searchd = array(
	            '1' => 'hot_main,hot_delta',
	            '2' => 'user_main,user_delta',
	            '3' => 'topic_main,topic_delta',
	    );
	    return $client->query($keyword, $searchd[3]);
	}
	
	// 从redis中获取圈子信息,不存在则从数据库中获取并重新加入reids
	public function groupAddRedis($gid){
		$data  =   $this->diaryListCacheModel->getGroupCache($gid);
		if(empty($data['avatar'])) {
		    $this->diaryListCacheModel->delGroupCache($gid);
		    $data = array();
        }
		// 缓存没有则从数据库获取,然后再加入缓存中
		if (empty($data)){
			$groupInfo =  $this->getGroupInfo(array('gid'=>$gid));
			if (empty($groupInfo)){
				return  array();
			}
			$data =  $this->groupCacheData($groupInfo);
			$this->diaryListCacheModel->addGroupCache($gid, $data);
		}
		$noDbInfo  = $this->diaryListCacheModel->getGroupNodbCache($gid);
		$result    = array_merge($data, $noDbInfo);
        // 此处需确认
		if (!empty($result) && intval($gid) > 0 && intval($gid) <= 50 && empty($result['cover'])){
		    $OS    = UK::checkOS(AC::$appInfoList[2]);
		    $d_url = AC::getProtocolUriByOS(AC::$cdn_url_d);
		    if ($OS == 1){
		        $result['cover'] = "{$d_url}/diary/group/icon/common/".$gid.".png";
		    }else{
		        $result['cover'] = "{$d_url}/diary/group/icon/default/".$gid.".png";
		    }
		}
		return $result;
	}
	
	/**
	 * 获取圈子分类列表
	 * @param number $id
	 * @param unknown $start
	 * @param unknown $length
	 * @retunr unknown
	 */
	public function getGroupCategories(){
	    $key    =   $this->groupCatsKeyPrefix . 0;
	    $where  =   array('status' => 0,'type'=>0);
	    $orderBy=   ' display DESC ';
	    $result =   Storage::getConditionManyData($key, $where, $orderBy);
	    return $result;
	}
	
	/**
	 * 获取圈子分类详情
	 * @param unknown $cid
	 * @return Ambigous <multitype:, unknown, boolean, mixed>
	 */
	public function getGroupCategoryInfo($cid){
	    $result = $this->diaryListCacheModel->getMysqlDataHashCache('group_category', $cid);
	    if (empty($result)){
	        $key    =   $this->groupCatsKeyPrefix . 0;
	        $where  =   array('status' => 0, 'cid' => $cid,'type'=>0);
	        $result =   Storage::getConditionData($key, $where);
	        $this->diaryListCacheModel->setMysqlDataHashCache('group_category', $cid, $result);
	    }
	    if (!empty($result) && intval($cid) > 0){
	        $d_url = AC::getProtocolUriByOS(AC::$cdn_url_d);
	        $result['icon_large'] = "{$d_url}/diary/group/icon_category/default/".$cid.".png";
	    }
	    return $result;
	}
	
	// 构建小组redis缓存结构
	private function groupCacheData($info){
		$data = array();
		$data['id']				=	strval($info['gid']);
		$data['gid']			=	strval($info['gid']);
		$data['uid']			=	strval($info['uid']);
		$data['name']			=	strval($info['name']);
		$data['category']		=	empty($info['category']) ? '0' : strval($info['category']);
		$data['introduction']	=	strval($info['introduction']);
		$data['cover']			=	strval($info['cover']);
		$data['topic_num']		=	strval($info['topic_num']);
		$data['member_num']		=	strval($info['member_num']);
		$data['status']			=	strval($info['status']);
		$data['time']			=	strval($info['time']);
		$data['top_tids']		=	strval($info['top_tids']);
		$data['mUid']		    =	strval($info['mUid']);
		$data['gtype']		    =	strval($info['gtype']);
        $data['mUids']          =   strval($info['mUids']);
        $data['extras']         =   strval($info['extras']);
        if(!empty($info['extras'])) {
            $extraInfo = UK::parseData($info['extras']);
            $data['avatar'] = isset($extraInfo['avatar']) ? $extraInfo['avatar'] : '';
        }
        $pre = AC::$cdn_url_img;
        if ($data['cover']) {
            $url_image = strpos($data['cover'], 'http',0);
            if($url_image === false){
                $data['cover'] = $pre . $data['cover'];
            }
        }
        if(empty($data['avatar'])){
            $data['avatar'] = $data['cover'];
        }else{
            $url_image = strpos($data['avatar'], 'http',0);
            if($url_image === false){
                $data['avatar'] = $pre . $data['avatar'];
            }
        }
	
		return $data;
	}
	
	// ==========================================点滴话题======================================
    
	/**
	 * 创建点滴话题
	 * @param unknown $param
	 * @return boolean|Ambigous <unknown, boolean, number, resource>
	 */
	public function  createDiaryTopic($uid, $name){
	    if (empty($uid) || strlen($name) < 1) {
	        AC::$errorNo    =   'DTM001';
	        return  FALSE;
	    }
	     
	    $data = array(
	        'uid'              =>  intval($uid),
	        'mUid'             =>  intval($uid),
	        'name'             =>  UK::getstr($name, 36,'',1),
	        'type'             =>  0,
	        'topic_num'        =>  1,
	        'max_member_num'   =>  1,
	        'status'           =>  AC::$diaryTopicCf['review_status'],
	        'time'             =>  AC::SERVER_TIME
	    );

	    $key    =   $this->groupKeyPrefix. 0;
	    $result =   Storage::addData($key, $data);
	    if (empty($result)) {
	        AC::$errorNo = 'GRM002';
	        return FALSE;
	    }
	     
	    return  $result;
	}
	
	/**
	 * 获取话题详情
	 * @param unknown $id
	 * @return boolean|Ambigous <multitype:, unknown, boolean>
	 */
	public function getDiaryTopicInfoByName ($name) {
	    if (strlen($name) < 1) {
	        AC::$errorNo    =   'DTM001';
	        return FALSE;
	    }
	     
	    $key   	   =   $this->groupKeyPrefix. 0;
	    $where     =   array('name' => $name);
	    $result	   =   Storage::getConditionData($key, $where);
	    return $result;
	}
	
	/**
	 * 获取话题详情
	 * @param unknown $id
	 * @return boolean|Ambigous <multitype:, unknown, boolean>
	 */
	public function getDiaryTopicInfo ($id) {
	    if (empty($id)) {
	        AC::$errorNo    =   'DTM001';
	        return FALSE;
	    }
	    
	    $result = $this->diaryListCacheModel->getDiaryTopicHash($id);
	    if (empty($result)) {
	        $key   	   =   $this->groupKeyPrefix. 0;
	        $where     =   array('gid' => $id,'gtype' => 0);
	        $result	   =   Storage::getConditionData($key, $where);
	        
	        if ($result) {
	           $this->diaryListCacheModel->addDiaryTopicHash($id, $result);
	        }
	    }
	    
	    return $result;
	}
	
	/**
	 * 点滴话题查看数/讨论数加1
	 * @param unknown $gid
	 * @param string $discuss
	 * @return boolean|Ambigous <boolean, number, resource>
	 */
	public function addDiaryTopicViewOrDiscussNum($gid, $discuss = false) {
	    if (empty($gid)) {
	        AC::$errorNo    =   'DTM001';
	        return  FALSE;
	    }
	    $key    =   $this->groupKeyPrefix. 0;
	    $where  =   array('gid' => $gid,'gtype' => 0);
	    $data   =   array('max_member_num' => 1);
	    if ($discuss) $data = array('topic_num' => 1);
	
	    $result =   Storage::changeNumValueAdd($key, $data, $where);
	    return $result;
	}
	
	/**
	 * 获取点滴话题列表
	 * @param unknown $type
	 * @return Ambigous <unknown, boolean, multitype:>
	 */
	public function getDiaryTopics($type, $id, $start, $length){
	    $cache = $this->diaryListCacheModel->getHotTypeTopics($type);
        if ($cache)return array_slice($cache, 0, $length);
        $length = 20;
	    $key    = $this->groupKeyPrefix . 0;
//	    $where  = " `gid` >= ".AC::$diaryTopicCf['start_id']." AND `status` = ".AC::$diaryTopicCf['pass_status']." AND `type` = ".$type;
	    $where  = " `status` = ".AC::$diaryTopicCf['pass_status']." AND gtype = 0 AND `type` = ".$type;
	    $orderBy=   ' member_num DESC ';
	    $result =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
	    $result && $this->diaryListCacheModel->setHotTypeTopics($type, $result);
	    $this->checkOrUpdateOfficialTopics($type);
	    return $result;
	}
	
	/**
	 * 重建官方话题列表
	 * @param unknown $type
	 * @return boolean
	 */
	private function checkOrUpdateOfficialTopics ($type) {
	    $officialTopics = $this->diaryListCacheModel->getDiaryTopicOfficialByHot();
	    if (empty($officialTopics) && $type == AC::$diaryTopicCf['official']) {
	        $key    = $this->groupKeyPrefix . 0;
	        //$where  = " `gid` >= ".AC::$diaryTopicCf['start_id']." AND `status` != ".AC::$diaryTopicCf['delete_status']." AND `type` = ".AC::$diaryTopicCf['official'];
	        $where  = " gtype = 0 AND `status` != ".AC::$diaryTopicCf['delete_status']." AND `type` = ".AC::$diaryTopicCf['official'];
	        $orderBy=   ' gid DESC ';
	        $result =   Storage::getConditionManyData($key, $where, $orderBy);
	        if ($result) {
	            foreach ($result as $value) {
	                $this->diaryListCacheModel->addDiaryTopicToOfficialSet($value['gid'], $value['member_num']);
	            }
	        }
	    }
	    
	    return true;
	}
	
	/**
	 * 搜索点滴话题
	 * @param unknown $info
	 * @return multitype:multitype:unknown
	 */
	public function getSearchDiaryTopics($key_word){ 
	    $url = 'http://redis-search.ffrj.net/search?k='.urlencode($key_word);
	    $json= UK::getHttpResponseGET($url);

	    $result = UK::parseData($json);
	    if ($result['result'] && $result['result']['lists'] && !isset($result['error_code'])) {
	        return $result['result']['lists'];
	    }
	    
	    return array();
	}

    /**
     * @param $param
     * @param int $sort
     * @return array
     */
    public function loopGroupListByGid ($param, $sort = 1) {
        if (empty($param)) return array();

        $result = array();
        foreach ($param as $key => $value) {
            $value = $this->getDiaryTopicInfo($key);
            $tmp = $this->assembleDataOfDiaryTopic($value);
            if (empty($tmp['id']) || strlen($tmp['name']) < 1) continue;
            $result[] = $tmp;
        }

        return $result;
    }


	/**
	 * 循环点滴话题列表
	 * @param unknown $param
	 * @return multitype:Ambigous <multitype:string , multitype:string multitype: NULL >
	 */
	public function loopGroupList ($param, $sort = 1) {
	    if (empty($param)) return array();
	
	    $result = array();
	    foreach ($param as $value) {
	        if (isset($value['ext'])) {
	            $value = $value['ext'];
	        }
	
	        $tmp = $this->assembleDataOfDiaryTopic($value);
	        if (empty($tmp['id']) || strlen($tmp['name']) < 1) continue;
	        $result[] = $tmp;
	    }

	    $sort && UK::sortArrByOneField($result, 'hot');
	    return $result;
	}

	/**
	 * 组装点滴话题详情结构
	 * @param unknown $info
	 * @return multitype:string multitype: NULL
	 */
	public function assembleDataOfDiaryTopic ($info) {
	    $result = array(
	        'id'        =>      '0',
	        'name'      =>      '',
	        'desc'      =>      '',
	        'hot'       =>      '1',
	        'type'      =>      '',
	        'view_num'  =>      '0',
	        'topic_num' =>      '0',
	        'uid'       =>      '1',
	        'banner'    =>      array(),
	        'img_small' =>      '',
	    	'status'    =>      '0',
	    	'me_follow' =>      false,
	        'time'      =>      strval(AC::SERVER_TIME)
	    );
	
	    UK::assembleReplacedFieldData($info, $result, array(
    	    'gid'           =>  'id',
    	    'name'          =>  'name',
    	    'introduction'  =>  'desc',
    	    'type'          =>  'type',
    	    'max_member_num'=>  'view_num',
    	    'topic_num'     =>  'topic_num',
    	    'uid'           =>  'uid',
    	    'cover'         =>  'img_small',
    	    'time'          =>  'time',
    	    'status'        =>  'status',
        ));
	    
	    $result['hot']      = $this->calculateHotOfDiaryTopic($result['id']);
	    $result['banner'][] = $this->getDiaryTopicBanner($result['id'], $info['extras']);
	    empty($result['img_small']) && $result['img_small'] = 'http://img.fenfenriji.com/95/48/86/Image/693165544.png';
	    $result['img_small'] = AC::getProtocolUriByOS($result['img_small']);

	    return $result;
	}
	
	/**
	 * 获取点滴话题banner信息
	 * @param unknown $topic_id
	 * @param unknown $extras
	 * @return Ambigous <multitype:string , multitype:NULL string >
	 */
	private function getDiaryTopicBanner ($topic_id, $extras) {
	    $banner = array(
	        'id'       =>  strval($topic_id),
	        'image'    =>  AC::getProtocolUriByOS(AC::$cdn_url_img).'/70/17/23/Image/D4EBD804-C28C-3D0B-B091-56E94C06523A.png',
	        'action'   =>  ''
	    );
	    
	    if ($extras && UK::isJSON($extras)) {
	        $extras = json_decode($extras, true);
	        if ($extras && $extras['banner'][0]) {
	            $banner['image'] = strval($extras['banner'][0]['image']);
	            $banner['image'] = AC::getProtocolUriByOS($banner['image']);
	        }
	    }
	    
	    return $banner;
	}

	/**
	 * 计算热度
	 * @param unknown $member_num
	 * @return string
	 */
	private function calculateHotOfDiaryTopic ($id) {
	    $hot = 0;
	    if (empty($this->officialHotDiaryTopics)) {
	        $this->officialHotDiaryTopics = $this->diaryListCacheModel->getDiaryTopicOfficialByHot();
	    }
	    
	    if (empty($this->commonHotDiaryTopics)) {
	        $this->commonHotDiaryTopics = $this->diaryListCacheModel->getDiaryTopicByHot();
	    }
	    
	    if (array_key_exists($id, $this->officialHotDiaryTopics)) {
	        $hot = $this->officialHotDiaryTopics[$id];
	    }else{
	        if (array_key_exists($id, $this->commonHotDiaryTopics)) {
	            $hot = $this->commonHotDiaryTopics[$id];
	        }
	    }
	    
	    $hot = $hot > 100 ? 100 : intval(abs($hot));
	    
	    return strval($hot);
	}
	
	/**
	 * 组装点滴话题列表数据
	 * @param unknown $info
	 * @return multitype:|multitype:string
	 */
	public function assembleDataOfDiaryListTopic ($info) {
	    if (empty($info['gid'])) return array();
	    
	    $result = array(
	        'id'        =>      '0',
	        'name'      =>      '',
	        'desc'      =>      '',
	        'type'      =>      '',
	        'img_small' =>      ''
	    );
	    
	    UK::assembleReplacedFieldData($info, $result, array(
    	    'gid'           =>  'id',
    	    'name'          =>  'name',
    	    'introduction'  =>  'desc',
    	    'type'          =>  'type',
    	    'cover'         =>  'img_small'
        ));
	    
	    if (empty($result['id'])) return array();
	    $topicInfo = $this->getDiaryTopicInfo($result['id']);
	    if (empty($topicInfo) || $topicInfo['status'] == AC::$diaryTopicCf['delete_status']) {
	        return array();
	    }
	    
	    $result['name'] = $topicInfo['name'];
	    return $result;
	}
	
}